package com.xl.makedata.db.utils;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public abstract class BaseJdbcSink {
    protected Connection connection;
    protected String sql;
    protected PreparedStatement ps;

    public BaseJdbcSink(String sql) throws SQLException {
        this.sql = sql;
        try {
            connection = getConnections();
            Write2Mysql();
            System.out.println(this.getClass().getName().split("\\$")[0] + "  is ok");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            assert connection != null;
            connection.close();
            if (ps != null) {
                ps.close();
            }
        }
    }

    private Connection getConnections() throws Exception {
        if (connection != null) {
            return connection;
        }
        InputStream resource = BaseJdbcSink.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties properties = new Properties();
        properties.load(resource);
        String url = properties.getProperty("url");
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");

        Class<?> aClass = Class.forName("com.mysql.cj.jdbc.Driver");

        Driver driver = (Driver) aClass.newInstance();

        DriverManager.registerDriver(driver);

        return DriverManager.getConnection(url, user, password);
    }

    public abstract void Write2Mysql() throws Exception;

    public Integer getLastId(String tableName, String idName) throws SQLException {
        String sql = "select max(`" + idName + "`) " + "from `" + tableName + "` order by `" + idName + "` desc limit 1";
        PreparedStatement statement = connection.prepareStatement(sql);
        ResultSet resultSet = statement.executeQuery();
        if (resultSet.next()) {
            return resultSet.getInt(1);
        }
        return 0;
    }
}
